<template>
  <view>
    <view class="cinema-top">
      <uni-icons
          type="left"
          size="30"
          @click="goBack"
          style="margin-right: 20rpx"
      ></uni-icons>
      <view class="tops-item">
        <view class="cinema-img">
          <image :src="filmInfo.logo"></image>
        </view>
        <view class="cinema-info">
          <view class="cinema-info-top">
            <view class="top-name">{{ filmInfo.name }}</view>
            <view class="top-type">{{ filmInfo.versionType }}</view>
          </view>
          <view class="rate-item">
            <text class="rate-nun">{{ filmInfo.grade }}</text>
          </view>
          <view class="list-type"
          >{{ filmInfo.type }} | {{ filmInfo.duration }}分钟
          </view
          >
          <view class="list-type">{{ filmInfo.playdate }} 上映</view>
        </view>
      </view>
    </view>

    <view class="cinema-down">
      <view class="down-city" @click="selectCity">
        <text>{{ position.name || "请选择城市" }}</text>
        <image src="https://picture-1326598115.cos.ap-nanjing.myqcloud.com/2025/09/24db001ebcaa394dc6a823f9393c74646bmovie-xiala.png"></image>
      </view>
      <view class="down-city" style="margin-left: 80rpx">
        <uni-data-select
            v-model="countyId"
            :localdata="countyList"
            @change="changeCounty"
        ></uni-data-select>
      </view>
    </view>

    <view
        class="cinema-list"
        v-for="(value, index) in dataList"
        :key="index"
        @click="getDataUrl(value)"
    >
      <view class="cinema-name">{{ value.name }}</view>
      <view class="cinema-address-item">
        <view class="address-text">{{ value.address }}</view>
      </view>
    </view>

    <!-- 加载更多提示 -->
    <view v-if="isLoading" style="text-align: center; padding: 20rpx; color: #636775;">
      加载中...
    </view>
  </view>
</template>

<script setup>
import {ref,watch} from 'vue';
import {onLoad, onReachBottom} from '@dcloudio/uni-app';
import sheep from "@/sheep";

// 响应式数据
const filmInfo = ref({});
const position = ref({});
const dataList = ref([]);
const page = ref(0); // 从1开始，而不是0
const pageSize = ref(10); // 每页加载数量
const isLoading = ref(false); // 加载状态锁
const hasMore = ref(true); // 是否有更多数据
const countyId = ref(0);
const countyList = ref([]);

watch(position, (newPos) => {
  if (newPos.id) {
    // 重置分页状态
    page.value = 1;
    dataList.value = [];
    hasMore.value = true;
    // 使用新位置ID重新加载影院列表
    getCinemaList(newPos.id, 1, 'cityCode');
  }
});

// 生命周期钩子 - 页面加载
onLoad((option) => {
  try {
    console.log("解析后参数:", option);
    filmInfo.value = option;
    position.value = uni.getStorageSync('xk-map');
    // 添加默认cityCode标识
    getCinemaList(position.value.id, 1, 'cityCode');
    getCountyList();
  } catch (error) {
    console.error("页面初始化失败:", error);
    uni.showToast({
      title: "页面加载失败",
      icon: "none"
    });
  }
});

// 生命周期钩子 - 触底加载
onReachBottom(() => {
  // 避免重复加载和无效加载
  if (hasMore.value && !isLoading.value) {
    page.value++;
    getPageData();
  } else if (!hasMore.value) {
    uni.showToast({
      title: "没有更多数据了",
      icon: "none"
    });
  }
});

// 方法 - 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1
  });
};

// 方法 - 切换县区
const changeCounty = (e) => {
  console.log('切换县区:', e);
  // 重置分页状态
  page.value = 1;
  dataList.value = [];
  hasMore.value = true;

  // 根据选择的值确定查询标识
  // 当选择"全城"(e=0)时使用cityCode，否则使用countyCode
  const flag = e === 0 ? 'cityCode' : 'countyCode';

  // 使用正确的标识获取影院列表
  getCinemaList(e === 0 ? position.value.id : e, 1, flag);
};

// 方法 - 获取县区列表
const getCountyList = async () => {
  try {
    countyList.value = [];
    // 添加"全城"选项
    countyList.value.push({
      value: 0,
      text: "全城"
    });

    const res = await sheep.$api.xkMovie.getCountyList({
      cityCode: position.value.id
    });

    if (res && res.data && res.data.countyList) {
      res.data.countyList.forEach(item => {
        countyList.value.push({
          value: item.id,
          text: item.name
        });
      });
    }
  } catch (error) {
    console.error("获取县区列表失败:", error);
    uni.showToast({
      title: "获取地区失败",
      icon: "none"
    });
  }
};

// 方法 - 获取影院列表
const getCinemaList = async (cityId, pageNumber = 1, cityCodeFlag = 'cityCode') => {
  // 防止重复请求
  if (isLoading.value) return;

  isLoading.value = true;
  try {
    const res = await sheep.$api.xkMovie.getCinemaList({
      cityCode: cityId || position.value.id,
      cityCodeFlag,
      page: pageNumber,
      size: pageSize.value
    });

    if (res && res.code === 200) {
      // 错误：从数组解构对象属性
      // const {content, totalElements, totalPages} = res.data || [];
      // 修复为：
      const data = res.data || {};
      const {content = [], totalElements, totalPages} = data;
      console.log('影院列表数据:', content);

      // 处理分页数据
      if (pageNumber === 1) {
        // 第一页，直接替换数据
        dataList.value = content;
      } else {
        // 分页加载，追加数据
        dataList.value.push(...content);
      }

      // 判断是否还有更多数据
      hasMore.value = content.length === pageSize.value;
    } else {
      throw new Error(res?.message || "获取影院列表失败");
    }
  } catch (error) {
    console.error("获取影院列表错误:", error);
    uni.showToast({
      title: error.message || "加载影院失败",
      icon: "none"
    });
  } finally {
    // 无论成功失败，都要释放加载锁
    isLoading.value = false;
  }
};

// 方法 - 获取分页数据
const getPageData = async () => {
  // 获取当前选中的城市/区域ID
  const currentCityId = countyId.value || position.value.id;
  // 根据是否选择区县动态设置查询标识
  const currentFlag = countyId.value ? 'countyCode' : 'cityCode';
  await getCinemaList(currentCityId, page.value, currentFlag);
};

// 方法 - 跳转到选择电影页面
const getDataUrl = (data) => {
  if (!data || !data.id) {
    console.error("无效的影院数据");
    uni.showToast({
      title: "数据异常",
      icon: "none"
    });
    return;
  }
  sheep.$router.go('/pages/xk-movie/choice-movie', {
    movieName: filmInfo.value.name,
    id: data.id
  })
};

// 方法 - 选择城市
const selectCity = () => {
  sheep.$router.go('/pages/xk-movie/address-city', {}, async (res) => {
    // 城市选择返回后重置为城市查询
    if (res && res.cityId) {
      // 1. 更新本地存储的城市信息
      const newCityData = {
        id: res.cityId,
        name: res.cityName || position.value.name
      };
      try {
        uni.setStorageSync('xk-map', newCityData);
        position.value = newCityData;
      } catch (e) {
        console.error('存储城市信息失败:', e);
      }

      // 2. 重置分页状态
      page.value = 1;
      dataList.value = [];
      hasMore.value = true;

      // 3. 重置区县选择为"全城"
      countyId.value = 0;

      try {
        // 4. 先显示加载状态
        // isLoading.value = true;

        // 5. 并行获取新城市的区县列表和影院列表
        const [countyResult] = await Promise.all([
          getCountyList(),
          getCinemaList(res.cityId, 1, 'cityCode')
        ]);

        // 6. 可以根据需要处理区县列表获取结果
        // console.log('新城市的区县列表:', countyResult);
      } catch (error) {
        console.error('更新城市信息失败:', error);
        uni.showToast({
          title: '更新城市信息失败',
          icon: 'none'
        });
      } finally {
        // 7. 确保加载状态被释放
        isLoading.value = false;
      }
    }
  });
};
</script>

<style lang="scss" scoped>
// 轮播区域样式优化
.cinema-top {
  background-color: #636775;
  padding: 120rpx 32rpx 32rpx;

  .tops-item {
    display: flex;
    align-items: center;
  }

  .cinema-img {
    width: 180rpx;
    height: 248rpx;

    image {
      width: 100%;
      height: 100%;
      border-radius: 20rpx;
      object-fit: cover;
    }
  }

  .cinema-info {
    margin-left: 30rpx;

    .cinema-info-top {
      display: flex;
      align-items: center;

      .top-name {
        color: #ffffff;
        font-size: 32rpx;
        font-weight: 600;
      }

      .top-type {
        background-color: #7b7b7b;
        border-radius: 6rpx;
        padding: 2rpx 8rpx;
        color: #ffffff;
        font-size: 17rpx;
        margin-left: 30rpx;
      }
    }

    .rate-item {
      display: flex;
      align-items: center;
      margin-top: 16rpx;

      .rate-nun {
        color: #ff6e06;
        font-size: 28rpx;
        font-weight: 550;
        margin-left: 16rpx;
      }
    }
  }
}

.list-type {
  color: #ffffff;
  font-size: 24rpx;
  margin-top: 12rpx;
}

.cinema-down {
  display: flex;
  align-items: center;
  padding: 22rpx 32rpx;
  border-bottom: 2rpx solid #dfe0e2;

  .down-city {
    display: flex;
    align-items: center;

    text {
      color: #636775;
      font-size: 28rpx;
    }

    image {
      width: 24rpx;
      height: 24rpx;
      margin-left: 8rpx;
    }
  }
}

.cinema-list {
  margin: 0rpx 32rpx;
  border-bottom: 2rpx solid #dfe0e2;
  padding: 32rpx 0rpx 40rpx 0rpx;
  transition: background-color 0.2s ease;

  &:active {
    background-color: #f5f5f5;
  }

  .cinema-name {
    color: #2d3039;
    font-size: 32rpx;
    font-weight: 550;
  }

  .cinema-address-item {
    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;

    .address-text {
      color: #636775;
      font-size: 24rpx;
      width: 78%;
      word-break: break-all;
    }

    .distance {
      color: #636775;
      font-size: 28rpx;
    }
  }
}
</style>
